import 'package:flutter/material.dart';
import 'package:shop_project/routers/application.dart';
import '../config/service_method.dart';
import 'dart:convert';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  String homePageContent = '暂无数据';
  int page = 1;
  List<Map> hotGoodsList = [];
  GlobalKey<RefreshFooterState> _footerKey = GlobalKey<RefreshFooterState>();

  // @override
  // void initState() {
  //   super.initState();
  // }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Scaffold(
        appBar: AppBar(
          title: Text('首页'),
        ),
        body: FutureBuilder(
          future: postRequest('homePageContent',
              data: {'lon': '115.02932', 'lat': '35.76189'}),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              var data = json.decode(snapshot.data.toString());
              List<Map> swiperDataList =
                  (data['data']['slides'] as List).cast();
              List<Map> navigatorList =
                  (data['data']['category'] as List).cast();
              String advertesPicture =
                  data['data']['advertesPicture']['PICTURE_ADDRESS'];
              String leaderImage = data['data']['shopInfo']['leaderImage'];
              String leaderPhone = data['data']['shopInfo']['leaderPhone'];
              List<Map> recommendList =
                  (data['data']['recommend'] as List).cast();
              String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS'];
              List<Map> floor1 = (data['data']['floor1'] as List).cast();
              String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS'];
              List<Map> floor2 = (data['data']['floor2'] as List).cast();
              String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS'];
              List<Map> floor3 = (data['data']['floor3'] as List).cast();
              return EasyRefresh(
                refreshFooter: ClassicsFooter(
                  key: _footerKey,
                  bgColor: Colors.white,
                  textColor: Colors.pink,
                  moreInfoColor: Colors.pink,
                  showMore: true,
                  noMoreText: '',
                  moreInfo: '...',
                  loadedText: '加载完毕',
                  loadingText: '加载中',
                  loadReadyText: '',
                  loadText: '上拉加载...',
                ),
                child: SingleChildScrollView(
                  child: Column(
                    children: <Widget>[
                      SwiperDIY(swiperDataList),
                      TopNavigator(navigatorList),
                      ADBanner(advertesPicture),
                      LeaderPhone(phone: leaderPhone, image: leaderImage),
                      Recommend(recommendList),
                      FloorTitle(floor1Title),
                      FloorContent(floor1),
                      FloorTitle(floor2Title),
                      FloorContent(floor2),
                      FloorTitle(floor3Title),
                      FloorContent(floor3),
                      _hotGoods()
                    ],
                  ),
                ),
                loadMore: _getHotGoods,
                // loadMore: () async {
                //   var formPage = {'page': page};
                //   await postRequest('homePageBelowContent', data: formPage)
                //       .then((onValue) {
                //     var data = json.decode(onValue.toString());
                //     List<Map> newGoodsList = (data['data'] as List).cast();
                //     setState(() {
                //       page++;
                //       hotGoodsList.addAll(newGoodsList);
                //     });
                //   });
                // },
              );
            } else {
              return Center(
                child: Text('加载中'),
              );
            }
          },
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  /**
   * 获取火爆专区内容
  */
  Future<void> _getHotGoods() async {
    var formPage = {'page': page};
    await postRequest('homePageBelowContent', data: formPage).then((onValue) {
      var data = json.decode(onValue.toString());
      List<Map> newGoodsList = (data['data'] as List).cast();
      setState(() {
        page++;
        hotGoodsList.addAll(newGoodsList);
      });
    });
  }

  Widget _hotGoods() {
    return Container(
      child: Column(
        children: <Widget>[hotTitle, _wrapList()],
      ),
    );
  }

  Widget hotTitle = Container(
    margin: EdgeInsets.only(top: 10),
    padding: EdgeInsets.all(5),
    alignment: Alignment.center,
    decoration: BoxDecoration(
        color: Colors.white,
        border: Border(bottom: BorderSide(width: 0.5, color: Colors.black26))),
    child: Text('火爆专区'),
  );

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List<Widget> listWidget = hotGoodsList.map((value) {
        return InkWell(
          onTap: () {
            Application.router
                .navigateTo(context, '/detail?id=${value['goodsId']}');
          },
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5),
            margin: EdgeInsets.only(bottom: 3),
            child: Column(
              children: <Widget>[
                Image.network(value['image'],
                    width: ScreenUtil().setWidth(370)),
                Text(
                  value['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                      color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${value['mallPrice']}'),
                    Text(
                      '￥${value['price']}',
                      style: TextStyle(
                          color: Colors.black26,
                          decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(spacing: 2, children: listWidget);
    } else {
      return Text(' ');
    }
  }
}

//轮播图
class SwiperDIY extends StatelessWidget {
  final List swiperDataList;
  SwiperDIY(this.swiperDataList);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(333),
      width: ScreenUtil().setWidth(750),
      child: Swiper(
        itemCount: swiperDataList.length,
        itemBuilder: (context, index) {
          return InkWell(
            onTap: () {
              Application.router.navigateTo(
                  context, '/detail?id=${swiperDataList[index]['goodsId']}');
            },
            child: Image.network(
              '${swiperDataList[index]['image']}',
              fit: BoxFit.fill,
            ),
          );
        },
        autoplay: true,
        pagination: SwiperPagination(),
      ),
    );
  }
}

//轮播图下边的选项列表
class TopNavigator extends StatelessWidget {
  final List navigatorList;
  TopNavigator(this.navigatorList) : super();

  Widget _gridViewItemUI(BuildContext context, item) {
    return InkWell(
      onTap: () {},
      child: Column(
        children: <Widget>[
          Image.network(item['image'], width: ScreenUtil().setWidth(95)),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    if (navigatorList.length > 10)
      navigatorList.removeRange(10, navigatorList.length);
    return Container(
      height: ScreenUtil().setHeight(300),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: navigatorList.map((i) {
          return _gridViewItemUI(context, i);
        }).toList(),
      ),
    );
  }
}

//广告条
class ADBanner extends StatelessWidget {
  final String advertesPicture;
  ADBanner(this.advertesPicture);
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(advertesPicture),
    );
  }
}

//店长电话啥的
class LeaderPhone extends StatelessWidget {
  final String phone;
  final String image;

  LeaderPhone({Key key, this.phone, this.image});

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: _launchURL,
        child: Image.network(image),
      ),
    );
  }

  void _launchURL() async {
    String url = 'tel:' + phone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw 'Could not launch $url';
    }
  }
}

//商品推荐
class Recommend extends StatelessWidget {
  final List recommendList;
  Recommend(this.recommendList);

  @override
  Widget build(BuildContext context) {
    return Container(
        height: ScreenUtil().setHeight(410),
        margin: EdgeInsets.only(top: 10.0),
        child: SingleChildScrollView(
          physics: NeverScrollableScrollPhysics(),
          child: Column(
            children: <Widget>[_titleWidget(), _recommedList()],
          ),
        ));
  }

  Widget _titleWidget() {
    return Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(10.0, 2.0, 0.5, 0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          '商品推荐',
          style: TextStyle(color: Colors.pink),
        ));
  }

  Widget _recommedList() {
    return Container(
        height: ScreenUtil().setHeight(410),
        child: ListView.builder(
          scrollDirection: Axis.horizontal,
          itemCount: recommendList.length,
          itemBuilder: (context, index) {
            return _item(context, index);
          },
        ));
  }

  Widget _item(context, index) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(
            context, '/detail?id=${recommendList[index]['goodsId']}');
      },
      child: Container(
        height: ScreenUtil().setHeight(410),
        width: ScreenUtil().setWidth(250),
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(left: BorderSide(width: 1, color: Colors.black12))),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('￥${recommendList[index]['mallPrice']}'),
            Text('￥${recommendList[index]['price']}',
                style: TextStyle(
                    decoration: TextDecoration.lineThrough, color: Colors.grey))
          ],
        ),
      ),
    );
  }
}

//楼层标题
class FloorTitle extends StatelessWidget {
  final String picture_address;
  FloorTitle(this.picture_address);
  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8),
      child: Image.network(picture_address),
    );
  }
}

//楼层内容
class FloorContent extends StatelessWidget {
  final List floorGoodList;
  FloorContent(this.floorGoodList);
  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[_firstRow(context), _otherRow(context)],
    );
  }

  Widget _goodsItem(context, goods) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: () {
          Application.router
              .navigateTo(context, '/detail?id=${goods['goodsId']}');
        },
        child: Image.network(goods['image']),
      ),
    );
  }

  Widget _firstRow(context) {
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodList[0]),
        Column(
          children: <Widget>[
            _goodsItem(context, floorGoodList[1]),
            _goodsItem(context, floorGoodList[2]),
          ],
        )
      ],
    );
  }

  Widget _otherRow(context) {
    return Row(
      children: <Widget>[
        _goodsItem(context, floorGoodList[3]),
        _goodsItem(context, floorGoodList[4]),
      ],
    );
  }
}
